package filter

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/emicklei/go-restful/v3"
	"github.com/rs/zerolog/log"
	"io/ioutil"
	"net/http"
	"time"
	"webGoDemo/common"
	"webGoDemo/utils"
)

func AuditLogFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {

	inBody, err := ioutil.ReadAll(req.Request.Body)
	if err != nil {
		_ = resp.WriteError(400, err)
		return
	}
	req.Request.Body = ioutil.NopCloser(bytes.NewReader(inBody))

	c := NewResponseCapture(resp.ResponseWriter)
	resp.ResponseWriter = c
	// 需要的参数
	//从如下的几个位置获取
	//1. 从header 中获取
	//2. 从response 中获取
	//3. 从路径上去
	//4 从请求参数上获取

	//六要素
	//ip := utils.GetRemoteClientIp(req.Request)

	//放行
	chain.ProcessFilter(req, resp)

	commonResp := new(common.Response)
	err = json.Unmarshal(c.body.Bytes(), commonResp)
	if err != nil {
		return
	}
	var result = ""
	if commonResp.Code == "0" {
		result = "Success"
	} else {
		result = "Fail"
	}
	//data := commonResp.Data
	//if data == nil {
	//
	//}
	userName := req.Request.Header.Get("userID")
	auditLog := &AuditLog{
		UserName:    userName,
		Host:        req.Request.URL.Host,
		Resource:    fmt.Sprintf("%v", req.Attribute("resource")),
		Method:      req.Request.Method,
		OperateTime: time.Now().Format("2006-01-02 15:04:05.000"),
		Result:      result,
		IP:          utils.GetRemoteClientIp(req.Request),
		JsonDetail:  commonResp.Data,
	}
	marshal, err := json.Marshal(auditLog)
	log.Info().Msg(string(marshal))
}

type AuditLog struct {
	UserName    string `json:"user_name,omitempty"`
	Resource    string `json:"resource,omitempty"`
	Host        string `json:"url,omitempty"`
	Method      string `json:"method,omitempty"`
	OperateTime string `json:"operate_time,omitempty"`
	Result      string `json:"result,omitempty"`
	// 附加的字段
	IP         string      `json:"ip,omitempty"`
	JsonDetail interface{} `json:"json_detail,omitempty"`
}

type ResponseLog struct {
	http.ResponseWriter
}

//func (r *ResponseLog) {
//
//}
